//#region interface
//#endregion interface
//@ts-ignore
var fs = require('fs');
var varTemp = "\n\t\t/** {desc} */\n\t\t{varName} : {varType};";
var interfaceTemp = "\t/** {desc} */\n\tinterface {name} {\n{varList} \n\t}\n";
function isArray(params) {
    return params && params.type === 'array';
}
function isObject(params) {
    return params && params.type === 'object';
}
//MARK: 解析返回数据
function getRes(json) {
    try {
        var schemaData = json.responses[200]['content']['application/json'];
        if (!schemaData) {
            schemaData = json.responses[200]['content']['*/*'];
        }
        if (schemaData.schema.properties) {
            return parseResProperties(schemaData.schema.properties);
        }
        else {
            console.log('parse schema');
        }
    }
    catch (error) {
        console.log('get res error', error);
    }
    return undefined;
}
function parseResProperties(propsObj) {
    var res = {};
    var hasKey = false;
    for (var key in propsObj) {
        var item = propsObj[key];
        switch (key) {
            //忽略这两个值
            case 'code':
            case 'msg':
                break;
            default:
                hasKey = true;
                if (isArray(item)) {
                    res[key] = parseArray(key, item.items.properties);
                }
                else {
                    res[key] = parseObject(key, item.properties);
                }
                break;
        }
    }
    if (hasKey) {
        return res;
    }
}
function parseArray(key, map) {
    var ret = { name: key, list: [], type: 'array' };
    for (var key_1 in map) {
        var item = map[key_1];
        item.name = key_1;
        if (isObject(item)) {
            var object = parseObject(key_1, item.properties);
            ret.list.push(object);
        }
        else if (isArray(item)) {
            if (item.items.properties) {
                //@ts-ignore
                var array = parseObject(key_1, item.items.properties);
                // array.type + '[]'
                ret.list.push(array);
            }
            else {
                var data = {
                    name: key_1,
                    description: item.description,
                    type: item.items.type + '[]',
                };
                ret.list.push(data);
            }
        }
        else {
            var data = {
                name: key_1,
                description: item.description,
                type: item.type,
            };
            ret.list.push(data);
        }
    }
    return ret;
}
function parseObject(varName, object) {
    var ret = { name: varName, list: [] };
    for (var key in object) {
        var item = object[key];
        item.name = key;
        if (isObject(item)) {
            var object_1 = parseObject(key, item.properties);
            ret.list.push(object_1);
        }
        else if (isArray(item)) {
            var object_2 = parseArray(key, item.items.properties);
            ret.list.push(object_2);
        }
        else {
            var data = {
                name: key,
                description: item.description,
                type: item.type,
            };
            ret.list.push(data);
        }
    }
    return ret;
}
function toTsType(type, desc) {
    var reg = /[a-zA-Z0-9\s\|]+/;
    switch (type) {
        case 'integer':
        case 'page':
            return 'number';
        case 'text':
        case 'string':
            if (reg.test(desc)) {
                var regRet = desc.match(reg);
                var list = regRet[0].split('|');
                for (var i = 0; i < list.length; i++) {
                    var item = list[i];
                    item = item.replace(/\s/g, '');
                    list[i] = "'" + item + "'";
                }
                return list.join('|');
            }
            return 'string';
        default:
            return type;
    }
}
function capitalizeFirstLetter(str) {
    return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
}
function url2InterfaceName(url) {
    var name = url.replace('/api/', '');
    name = name.replace(/^\//g, '');
    name = name.replace(/\//g, '_');
    return capitalizeFirstLetter(name);
}
function parseReqVars(reqList) {
    var varStrList = [];
    var list = reqList || [];
    list.forEach(function (item) {
        var temp = varTemp.replace('{varName}', item.name);
        temp = temp.replace('{varType}', toTsType(item.schema.type, item.description));
        temp = temp.replace('{desc}', item.description);
        varStrList.push(temp);
    });
    return varStrList;
}
function parseResVars(resObj) {
    var _loop_1 = function (key) {
        var item = resObj[key];
        var resVarList = item.list || [];
        var varStrList = [];
        resVarList.forEach(function (inner) {
            var temp = varTemp.replace('{varName}', inner.name);
            temp = temp.replace('{varType}', toTsType(inner.type, inner.description));
            temp = temp.replace('{desc}', inner.description);
            varStrList.push(temp);
        });
        return { value: varStrList };
    };
    for (var key in resObj) {
        var state_1 = _loop_1(key);
        if (typeof state_1 === "object")
            return state_1.value;
    }
    return [];
}
function toDtsString(list) {
    var retList = [];
    list.forEach(function (item) {
        var className = url2InterfaceName(item.url);
        //#region parse req
        var reqVarStrList = parseReqVars(item.reqList);
        if (reqVarStrList.length > 0) {
            var interfaceReqStr = interfaceTemp.replace('{name}', className + 'Req');
            interfaceReqStr = interfaceReqStr.replace('{varList}', reqVarStrList.join('\n'));
            interfaceReqStr = interfaceReqStr.replace('{desc}', item.summary + ' 请求数据');
            retList.push(interfaceReqStr);
        }
        //#endregion parse req
        //#region parse res
        var resVarStrList = parseResVars(item.resObj);
        var interfaceResStr = interfaceTemp.replace('{name}', className + 'Res');
        interfaceResStr = interfaceResStr.replace('{varList}', resVarStrList.join('\n'));
        interfaceResStr = interfaceResStr.replace('{desc}', item.summary + ' 返回数据');
        retList.push(interfaceResStr);
        //#endregion parse res
        var interfaceHttpStr = interfaceTemp.replace('{name}', className + 'Http');
        interfaceHttpStr = interfaceHttpStr.replace('{desc}', item.summary);
        var url = "\t\turl: \"".concat(item.url, "\";\n");
        var method = "\t\tmethod: \"".concat(item.method, "\";\n");
        var resHttpStr = '';
        if (resVarStrList.length > 0) {
            var resType = "".concat(className, "Res");
            if (item.resObj && item.resObj.result && item.resObj.result.type === 'array') {
                resType += '[]';
            }
            resHttpStr = "\t\tres?: Res<".concat(resType, ">;");
        }
        var reqHttpStr = '';
        if (reqVarStrList.length > 0) {
            reqHttpStr = "\t\tdata: ".concat(className, "Req;\n");
        }
        var typeCodeRet = returnCode2TS(className + 'Http', item.returnCodeList);
        var codeVar = '';
        if (typeCodeRet) {
            codeVar = '\t\tcode?: ' + typeCodeRet.name + ";\n";
            interfaceHttpStr = typeCodeRet.declare + interfaceHttpStr;
        }
        interfaceHttpStr = interfaceHttpStr.replace('{varList}', url + method + codeVar + reqHttpStr + resHttpStr);
        retList.push(interfaceHttpStr);
    });
    return retList;
}
//#region return code
function parseReturnCode(json) {
    var list = [];
    try {
        for (var key in json.responses) {
            var item = json.responses[key];
            var data = {
                code: parseInt(key),
                description: item.description,
            };
            list.push(data);
        }
    }
    catch (error) {
        console.log('parse return code error', error);
    }
    return list;
}
function returnCode2TS(name, list) {
    try {
        var ret = {};
        var retList = [];
        ret.name = '';
        ret.declare = '';
        var str_1 = '';
        var allList_1 = [];
        list.forEach(function (item) {
            str_1 += "\t/** ".concat(item.description, " */\n");
            var typeName = "".concat(name, "_").concat(item.code);
            str_1 += "\ttype ".concat(typeName, " = ").concat(item.code, ";\n");
            allList_1.push(typeName);
        });
        retList.push(str_1);
        var typeCode = "TypeCode_".concat(name);
        var all = "\ttype ".concat(typeCode, " = ") + allList_1.join('|');
        ret.name = typeCode;
        ret.declare = retList.join('\n') + '\n' + all + ';\n';
        return ret;
    }
    catch (error) {
    }
    return undefined;
}
//#endregion return code
//@ts-ignore
var http = require('http');
function getHttpJson(callback) {
    http.get('http://www.chat.com/index/index/doc', function (res) {
        var data = '';
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            callback(JSON.parse(data));
        });
    }).on('error', function (err) {
        console.error('请求错误:', err);
        callback(undefined);
    });
}
function readLocalJson(callback) {
    try {
        var txt = fs.readFileSync('./feiwuxingren.json', 'utf8');
        var json = JSON.parse(txt);
        callback(json, true);
    }
    catch (error) {
        console.log('load local json error', error);
    }
}
function doRun(json, noWrite) {
    var list = [];
    try {
        if (!noWrite) {
            fs.writeFileSync('./api.json', JSON.stringify(json, null, 2), 'utf8');
        }
        for (var key in json.paths) {
            var item = json.paths[key];
            var _loop_2 = function (i) {
                var inner = item[i];
                var obj = { url: key.replace('/api', ''), method: i };
                obj.reqList = [];
                if (inner.parameters) {
                    inner.parameters.forEach(function (param) {
                        if (param.name !== 'user-token') {
                            obj.reqList.push(param);
                        }
                    });
                }
                obj.summary = inner.summary;
                obj.resObj = getRes(inner);
                obj.returnCodeList = parseReturnCode(inner);
                list.push(obj);
            };
            for (var i in item) {
                _loop_2(i);
            }
        }
        if (list.length > 0) {
            var retList = toDtsString(list);
            // if (retList.length > 0) {
            //     console.log(retList[0]);
            // }
            var namespaceHead = 'declare namespace msg.auto {\n';
            var namespaceTail = '}';
            var filePath = 'E:/workplace/same-city/charm-of-same-city/src/types/auto';
            fs.writeFileSync(filePath + '/msg_auto.d.ts', namespaceHead + retList.join('\n') + namespaceTail, 'utf-8');
        }
    }
    catch (error) {
        console.log('error', error);
    }
}
function run() {
    // getHttpJson(doRun);
    readLocalJson(doRun);
}
run();
